package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 练习反射操作注解
public class Test8 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        // 通过反射获取对象
        Class<?> c1 = Class.forName("reflection.Student");
        // 通过对象获取注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        /*
            @reflection.TableKuang(value=db_student)
         */
        // 获得注解指定的值
        TableKuang tableKuang = c1.getAnnotation(TableKuang.class);
        System.out.println(tableKuang.value());
        /*
            db_student
         */
        // 获得类指定的注解
        Field f = c1.getDeclaredField("id");
        FieldKuang annotation = f.getAnnotation(FieldKuang.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
        /*
            db_id
            int
            10
         */

    }

}


// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableKuang{
    String value();
}


// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldKuang{
    String columnName();
    String type();
    int length();
}

// 通过注解操作数据库
@TableKuang("db_student")
class Student{
    @FieldKuang(columnName = "db_id", type = "int", length = 10)
    private int id;
    @FieldKuang(columnName = "db_age", type = "int", length = 10)
    private int age;
    @FieldKuang(columnName = "db_name", type = "varchar", length = 10)
    private int name;

    public Student() {
    }

    public Student(int id, int age, int name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getName() {
        return name;
    }

    public void setName(int name) {
        this.name = name;
    }
}
